package com.cenntro.common.door;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SocketUtil {

	public static Map<String, Socket> socketPool = new HashMap<String, Socket>();

	private static SocketUtil INSTANCE = null;

	public static SocketUtil GetInstance() {
		if (INSTANCE == null) {
			INSTANCE = new SocketUtil();
		}
		return INSTANCE;
	}

	public String SendMsg(String command, String ipport) {
		String result = "";
		if (ipport.equals(""))
			return "参数错误";
		try {
			Socket _socket = null;
			String Ip = ipport.split(":")[0];
			Integer Port = Integer.valueOf(ipport.split(":")[1]);

			BufferedReader input = null;
			PrintWriter out = null;
			// 取连接
			if (!socketPool.containsKey(ipport)) {
				_socket = new Socket(Ip, Port);
				socketPool.put(ipport, _socket);
			} else {
				_socket = socketPool.get(ipport);
			}

			try {
				// 发送数据
				input = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
				out = new PrintWriter(_socket.getOutputStream(), true);
				out.println(command);
				char[] sn = new char[1000];
				input.read(sn);
				result = String.valueOf(sn).trim();
				if (result.equals("")) {
					_socket.close();
					_socket = new Socket(Ip, Port);
					input = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
					out = new PrintWriter(_socket.getOutputStream(), true);
					out.println(command);
					input.read(sn);
					result = String.valueOf(sn).trim();
				}
				// System.out.println("socketpool.SendMsg:" + command + "
				// result:" + result);
			} catch (Exception ex) {
				try {
					// 第一次发送失败，关掉重联再重发
					_socket.close();
					_socket = new Socket(Ip, Port);
					input = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
					out = new PrintWriter(_socket.getOutputStream(), true);
					out.println(command);
					char[] sn = new char[1000];
					input.read(sn);
					result = String.valueOf(sn).trim();
					// 重发成功，更新连接
					socketPool.put(ipport, _socket);
				} catch (Exception ex1) {
					// 重发不成功，返回失败
					return "error";
				}
			}
		} catch (Exception ex) {
			return "参数错误";
		}
		return result;

	}

}
